
package ch.hearc.coursJava.kitBase.de.wrapper;

import ch.hearc.coursJava.kitBase.tools.TabTools;
import ch.hearc.coursJava.moo.chrono.Chrono;

public class UseLancerDeObjet
	{

	/*------------------------------------------------------------------*\
	|*							Methodes Public							*|
	\*------------------------------------------------------------------*/

	public static void main(String[] args)
		{
		main();
		}

	public static void main()
		{
		int nbPasses = 1000000;
		long timeMonoThread = useMonoThread(nbPasses);
		long timeMultiThread= useQuadriThread(nbPasses);

		System.out.println("Time mono thread: " + timeMonoThread);
		System.out.println("Time multi thread: " + timeMultiThread);
		}

	/*------------------------------------------------------------------*\
	|*							Methodes Private						*|
	\*------------------------------------------------------------------*/

	private static long useQuadriThread(int nbPasse)
		{
		Chrono chrono = new Chrono();
		int nbFaces = 6;
		int nbLancerTotal = 0;
		int nbCoeurs = Runtime.getRuntime().availableProcessors();
		int nbPasses = nbPasse / nbCoeurs;

		LancerDe[] tabLancerDe = new LancerDe[nbCoeurs];

		for(int i = 1; i <= nbCoeurs; i++)
			{
			tabLancerDe[i - 1] = new LancerDe(nbFaces, nbLancerTotal, nbPasses);
			}

		Thread[] tabThread = new Thread[nbCoeurs];

		for(int i = 1; i <= nbCoeurs; i++)
			{
			tabThread[i - 1] = new Thread(tabLancerDe[i - 1]);
			}

		for(Thread threadi:tabThread)//Appel asynchrone. (appel non-bloquant)
			{
			threadi.start();
			}

		try
			{

			for(Thread threadi:tabThread)
				{
				threadi.join();//Attend que le thread i soit fini.
				}

			int[] tabResultat = new int[nbCoeurs];

			int i = 1;
			for(LancerDe lanceri:tabLancerDe)
				{
				tabResultat[i - 1] = lanceri.getNbLancersNecessaires();
				i++;
				}

			int moyenne = moyenneCeil(tabResultat);
			//chrono.pause();
			TabTools.afficher(tabResultat);

			System.out.println(moyenne);
			}
		catch (InterruptedException e)
			{
			System.err.println("Probleme join.");
			}
		return chrono.getTime();
		}

	private static int moyenneCeil(int[] tabInt)
		{
		int somme = 0;
		for(int elem:tabInt)
			{
			somme += elem;
			}
		return (int)Math.ceil(somme / (double)tabInt.length);
		}

	private static long useMonoThread(int nbPasses)
		{
		Chrono chrono = new Chrono();
		int nbFaces = 6;
		int nbLancerTotal = 0;

		LancerDe lancerDe = new LancerDe(nbFaces, nbLancerTotal, nbPasses);

		lancerDe.run();

		int nbLancersNecessaires = lancerDe.getNbLancersNecessaires();
		//chrono.pause();
		System.out.println(nbLancersNecessaires);
		return chrono.getTime();
		}

	}
